# -*- coding: utf-8 -*-

from util.functions import *

from BeautifulSoup import BeautifulSoup as bf

class MapChart:
      defaults = {"legend-spacing":20, "legend-x": None, "legend-y": None, "legend-rect-w": 15, "legend-rect-h": 10, "legend-rect-x": 0, "legend-rect-y": 0, "legend-text-x": 20, "legend-text-y": 11, "legend-text-size": "15px", "legend-title-x": 0, "legend-title-y": 0, "legend-title-size": "15px", "legend-title": "", "file-title":""}
      def __init__(self, data, config = {}):
          self.data = data
          self.config = config
          self._fillConfig()
          self.legend = None

      def _fillConfig(self):
          for d in self.defaults:
              if d not in self.config:
                 self.config[d] = self.defaults[d]

      def mapdata(self, inp):
         with open(inp) as f:
           sopa = bf(f.read())
         dictionary = {}
         for x in sopa.findAll(["path"]):
               try:
                 if x.title:
                    dictionary["".join([unicode(y) for y in x.title.contents])] = x["id"]
                 else: print x.title
               except Exception,e:
                 pass

         return dictionary, sopa

      def draw(self, inpfile, output):
          dic, soup = self.mapdata(inpfile.fname)
          for i in self.data:
              ID = dic[i]
              current = soup.findAll(attrs={"id":ID})[0]
              tots = current["style"].split(";")
              nous = []
              for y in tots:
                  if y.split(":")[0] == "fill":
                     nous.append("fill:"+rgb2hex(self.data[i]))
                  else: nous.append(y)
              current["style"] = ';'.join(nous)
          if self.config["legend-x"]: X = self.config["legend-x"]
          else: X = inpfile.x
          if self.config["legend-y"]: X = self.config["legend-x"]
          else: Y = inpfile.y
          if self.legend:
             if self.config["legend-title"]:
                title = """<g transform="translate(%s,%s)"><text x = "%d" y = "%d" id="text2987" style="font-size:%s;line-height:125%%;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;font-family:Liberation Sans;">%s</text></g>"""
                soup.findAll(["svg"])[0].append(title%(X,Y,self.config["legend-title-x"],self.config["legend-title-y"],self.config["legend-title-size"],self.config["legend-title"]))
                Y += self.config["legend-spacing"]
             template = """<g transform="translate(%s,%s)"><rect width="%d" height="%d" x = "%d" y = "%d" id="rect2985" style="fill:%s;fill-opacity:1;stroke:none" /><text x = "%d" y = "%d" id="text2987" style="font-size:%s;line-height:125%%;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;font-family:Liberation Sans;">%s</text></g>"""
             for l in self.legend:
                 temp = template%(X,Y,self.config["legend-rect-w"],self.config["legend-rect-h"],self.config["legend-rect-x"],self.config["legend-rect-y"],rgb2hex(l[0]),self.config["legend-text-x"],self.config["legend-text-y"],self.config["legend-text-size"],l[1])
                 soup.findAll(["svg"])[0].append(temp)
                 Y+= self.config["legend-spacing"]
          if self.config["file-title"]:
             soup.findAll(attrs={"id":"filetitle"})[0].contents[0].replaceWith(self.config["file-title"])
          with open(output,"w") as f: f.write(str(soup))
